package com.iman.locker.view;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iman.dao.User;
import com.iman.locker.Constant;
import com.iman.locker.MyApp;
import com.iman.locker.R;
import com.iman.locker.view.fragment.AuthenticationFragment;
import com.iman.locker.view.fragment.AuthorizeListener;
import com.iman.locker.view.fragment.DrawAuthenticationFragment;
import com.iman.locker.view.fragment.PinAuthenticationFragment;

import java.io.IOException;


/**
 * 锁页面
 * Created by esirong on 2015-12-04.
 */
public class LockActivity extends BaseActivity implements AuthorizeListener {
    public static final int TAB_FACE_TO_UNLOCK = Constant.LOCK_TYPE_FACE;
    public static final int TAB_DRAW_TO_UNLOCK = Constant.LOCK_TYPE_DRAW;
    public static final int TAB_PIN_TO_UNLOCK = Constant.LOCK_TYPE_PIN;
    private static final String TAG = "LockActivity";

    private AuthenticationFragment drawAuthenticationFragment;
    private AuthenticationFragment pinAuthenticationFragment;
    private int currentTab = TAB_FACE_TO_UNLOCK;
    private String appPackageName;
    private boolean isInLocking = false;//这个锁的是不是在工作状态（默认为false)
    private static final String LOCKER_STATUS = "lockerStatus";
    public static final String LOCK_TYPE = "lockType";
    public static final String LOCK_APP = "lockApp";

    ImageView appIconView;
    TextView appLabelView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
        getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        getWindow().setType(WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW);
        setContentView(R.layout.activity_lock);
        //使用toolbar来替换Actionbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        appIconView = (ImageView) findViewById(R.id.iv_app_icon);
        appLabelView = (TextView) findViewById(R.id.tv_app_label);

        if (getIntent() != null) {
            currentTab = getIntent().getIntExtra(LOCK_TYPE, TAB_DRAW_TO_UNLOCK);
            appPackageName = getIntent().getStringExtra(LOCK_APP);
            isInLocking = getIntent().getBooleanExtra(LOCKER_STATUS, false);
        }

        initLockerFragment();
        initAppInfo(appPackageName);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            currentTab = intent.getIntExtra(LOCK_TYPE, TAB_DRAW_TO_UNLOCK);
            appPackageName = intent.getStringExtra(LOCK_APP);
            isInLocking = intent.getBooleanExtra(LOCKER_STATUS, false);
        }
    }

    /**
     * 显示锁定的页面
     *
     * @param context 上下文
     */
    public static void showLocker(Context context, String appPackageName) {
        Intent intent = new Intent(context, LockActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(LOCK_APP, appPackageName);
        intent.putExtra(LOCKER_STATUS, true);
        context.startActivity(intent);
    }

    /**
     * 编辑锁定的页面
     *
     * @param context 上下文
     */
    public static void editLocker(Context context) {
        Intent intent = new Intent(context, LockActivity.class);
        intent.putExtra(LOCKER_STATUS, false);
        context.startActivity(intent);
    }

    /**
     * 初始化应用信息，包括其图标，标题等
     *
     * @param protectedAppName 应用包名
     */
    private void initAppInfo(String protectedAppName) {
        if (TextUtils.isEmpty(protectedAppName)) {
            return;
        }
        PackageManager pm = getPackageManager();
        ApplicationInfo info;
        try {
            info = pm.getApplicationInfo(protectedAppName, PackageManager.GET_META_DATA);
            appLabelView.setText(pm.getApplicationLabel(info));
            appIconView.setImageDrawable(pm.getApplicationIcon(info));

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化锁的类型页面（根据类型加载不同的密码锁)
     */
    private void initLockerFragment() {
        switch (currentTab) {
            case TAB_FACE_TO_UNLOCK:
                currentTab = TAB_FACE_TO_UNLOCK;
                break;
            case TAB_DRAW_TO_UNLOCK:
                if (drawAuthenticationFragment == null) {
                    drawAuthenticationFragment = DrawAuthenticationFragment.instance(!isInLocking);
                }
                showFragment(drawAuthenticationFragment, false);
                currentTab = TAB_DRAW_TO_UNLOCK;
                break;
            case TAB_PIN_TO_UNLOCK:
                if (pinAuthenticationFragment == null) {
                    pinAuthenticationFragment = PinAuthenticationFragment.instance(!isInLocking);
                }
                showFragment(pinAuthenticationFragment, false);
                currentTab = TAB_PIN_TO_UNLOCK;
                break;


        }
    }

    /**
     * 显示这个
     */
    public void showFragment(Fragment fragment, boolean backup) {
        FragmentTransaction localFragmentTransaction = getSupportFragmentManager().beginTransaction();
//        localFragmentTransaction.setCustomAnimations(2130968587, 2130968588, 2130968585, 2130968586);
        String str = fragment.getClass().getName();
        localFragmentTransaction.replace(R.id.fl_content, fragment, str);
        if (backup) {
            localFragmentTransaction.addToBackStack(str);
        }
        localFragmentTransaction.commit();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (isInLocking) {
            backToHome();
        }
        finish();
    }

    /**
     * 退回到桌面
     */
    private void backToHome() {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.HOME");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addCategory("android.intent.category.MONKEY");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
//        SystemClock.sleep(200);//增加0.2秒的延时，使得开桌面后再关闭锁，画面看不到被屏后的应用
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_lock, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_find_password:
                //找回密码
                toAccount();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private boolean toAccount() {
        //unlock the phone with an account password if they forget the lock pattern.
        boolean result;
        AccountManager am = AccountManager.get(this);
        Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
        if (accounts.length > 0) {
            result = true;
        } else {
            Toast.makeText(this, R.string.error_not_associated_google_account, Toast.LENGTH_SHORT).show();
            result = false;
        }
        for (Account account : accounts) {
            Bundle bundle = new Bundle();
            am.confirmCredentials(account, bundle, this, new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        //根据验证结果来确认用户是不是合法。
                        boolean is = future.getResult().getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
                        if (!is) {
                            Toast.makeText(LockActivity.this, R.string.msg_Security_verify_passed, Toast.LENGTH_SHORT).show();
                            clearPassword();
                        } else {
                            Toast.makeText(LockActivity.this, R.string.msg_security_failed, Toast.LENGTH_SHORT).show();

                        }

                    } catch (OperationCanceledException | IOException | AuthenticatorException e) {
                        e.printStackTrace();
                    }

                }

            }, new Handler());
            //此处省略
        }
        return result;
    }

    /**
     * 清删除用户的密码(手势密码，PIN密码)
     */
    private void clearPassword() {
        User user = MyApp.getInstance().getUser();
        user.setPasswordPin(null);
        user.setPasswordDraw(null);
        MyApp.getInstance().setUser(user);
    }

    @Override
    public void onAuthorizeDone(boolean result) {
        if (result) {
            finish();
        }
    }
}
